const lib = require("../lib")
const path = require("path");
const mongoConnected = require("../lib/mongoose_connect");
const mongoModels = require("../lib/mongoose_schemas");
const runPara = require("run-parallel-limit");
const fs = require("fs-extra");
const lodash = require("lodash");
// const path = require("path");

mongoConnected.then(_ => {
  console.log(Date.now(), Date());
  mongoModels.Match.find({
    map_name: "Savage_Main",
    team_size: 4
  })
    // .limit(150)
    .then(async matches => {
      console.log("这里有", matches.length, "场次");
      debugger
      // let first_match_id = matches[0].match_id;
      let match_ids = matches.map(e => e.match_id);
      let kill_events = await mongoModels.Event.find({
        _T: "LogPlayerKill",
        match_id: {
          $in: match_ids
        }
      });
      debugger
      let withKillerAndVictim = kill_events.filter(e => e._doc.killer
        && e._doc.victim.location.x
        && e._doc.killer.location.x
        && e._doc.attackId > 0).map(e => e._doc);
      // let attackIds = withKillerAndVictim
      let groggy_events = await mongoModels.Event.find({
        _T: "LogPlayerMakeGroggy",
        match_id: {
          $in: match_ids
        }
      });
      let withAttackerGroggyEvents = groggy_events.filter(e => e._doc.attacker
        && e._doc.victim.location.x
        && e._doc.attacker.location.x
        && e._doc.attackId > 0).map(e => e._doc)
      let diedImmediately = withKillerAndVictim.filter(e => {
        let find = withAttackerGroggyEvents.find(e1 => e1.match_id == e.match_id && e1.attackId == e.attackId);
        if (find) {
          // debugger
          return false;
        }
        return true
      });
      let diedImmediatelyInZone = diedImmediately.filter(e => e.victim.zone.length);
      let groggyInZones = withAttackerGroggyEvents.filter(e => e.victim.zone.length);
      let zones = {};
      for (let ev of diedImmediatelyInZone) {
        let loc = ev.victim['location'];
        let zoneNames = ev.victim['zone'];
        for (let zn of zoneNames) {
          if (!zones[zn]) {
            zones[zn] = []
          }
          zones[zn].push(loc);
        }
      }
      for (let ev of groggyInZones) {
        let loc = ev.victim['location'];
        let zoneNames = ev.victim['zone'];
        for (let zn of zoneNames) {
          if (!zones[zn]) {
            zones[zn] = []
          }
          zones[zn].push(loc);
        }
      }

      debugger

      // let withoutKiller = kill_events.filter(e => !e._doc.killer).map(e => e._doc);
      await fs.writeFile(path.join(__dirname, "./Savage_Main_Squad_DownInZone.json"), JSON.stringify(zones))

      debugger
    })
}).catch(err => {
  debugger
})
